package de.dopichaj.labrador.index.lucene;

import java.io.Reader;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;

/**
 * An analyzer that caches the result of another analyzer so that you can
 * access the tokens several times.
 */
public final class ReplayAnalyzer extends Analyzer {

    private final List<String> tokens;
    
    public ReplayAnalyzer(List<String> tokens) {
        
        this.tokens = tokens;
    }
    
    private static final class CachingStream extends TokenStream {

        private final List<String> tokens;
        private int pos = 0;
        private int textPos = 0;
        public CachingStream(List<String> tokens) {
            this.tokens = tokens;
        }
        
        @Override
        public Token next() {
            if (pos < tokens.size()) {
                final String text = tokens.get(pos++);
                final int endPos = textPos + text.length();
                final Token token = new Token(text, textPos, endPos);
                textPos = endPos + 1;
                return token;
            } else {
                return null;
            }
        }
    }
    
    /**
     * Get a token stream fed by the cached tokens.
     * @see org.apache.lucene.analysis.Analyzer#tokenStream(java.lang.String, java.io.Reader)
     */
    @Override
    public TokenStream tokenStream(String arg0, Reader arg1) {
        return new CachingStream(tokens);
    }
    
    /**
     * Get the number of tokens.
     */
    public int getTokenCount() {
        return tokens.size();
    }
    
}
/*
Copyright (c) 2005-2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/